import asyncio
import json
import aiohttp

MCP_SERVER_URL = "http://127.0.0.1:9985/sse"


async def fetch_tools():
    """
    连接到 MCP 服务端并获取可用的工具列表。
    """
    headers = {
        "Accept": "text/event-stream",
    }

    async with aiohttp.ClientSession() as session:
        async with session.get(MCP_SERVER_URL, headers=headers) as response:
            if response.status != 200:
                raise Exception(f"连接失败，状态码：{response.status}")

            print("✅ 已连接到 MCP 服务端。")

            async for line in response.content:
                if line:
                    event_data = line.decode('utf-8').strip()
                    if event_data.startswith("data:"):
                        try:
                            data_json = event_data[5:].strip()
                            data = json.loads(data_json)

                            # 检查是否为 tools 列表响应
                            if 'method' in data and data['method'] == 'list_tools':
                                tools = data.get('params', {}).get('tools', [])
                                print("\n🔧 可用工具列表:")
                                for tool in tools:
                                    print(f" - {tool['name']}: {tool['description']}")
                                return tools
                        except json.JSONDecodeError:
                            continue


async def main():
    try:
        await fetch_tools()
    except Exception as e:
        print(f"\n❌ 错误：{e}")


if __name__ == "__main__":
    asyncio.run(main())
